package com.chuantou.yuba.ui.fragment;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.baidu.location.BDLocation;
import com.chuantou.yuba.R;
import com.chuantou.yuba.YBApp;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.BaseGsonRequest;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.BaseTO;
import com.chuantou.yuba.api.to.FishingFriendDataTO;
import com.chuantou.yuba.api.to.FishingFriendTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.ui.LoginActivity;
import com.chuantou.yuba.ui.widget.LoadingView.Style;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.ActivityHelper;
import com.chuantou.yuba.util.BitmapBinder;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.DateUtil;
import com.chuantou.yuba.util.UiUtil;
import com.chuantou.yuba.util.ViewHolder;

public class NearFishingFriendFragment extends NearFilterFragment<FishingFriendDataTO> {
	private BDLocation mLocation;
	private FishingFriendAdapter mAdapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mLocation = YBApp.get().getLocation();
		mContext.registerReceiver(mLoginReceiver, new IntentFilter(Constants.INTENT_ACITON_LOGIN));
	}

	private BroadcastReceiver mLoginReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			load(1);
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View contentView = super.onCreateView(inflater, container, savedInstanceState);
		if (mAdapter == null) {
			mAdapter = new FishingFriendAdapter();
			mListView.setAdapter(mAdapter);
			mListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					Object obj = parent.getItemAtPosition(position);
					if (obj != null && obj instanceof FishingFriendTO) {
						FishingFriendTO friend = (FishingFriendTO) obj;
						ActivityHelper.toProfileActivity(getActivity(), friend.getUid());
					}
				}
			});
			startRequest();
		}
		return contentView;
	}

	@Override
	public void onDestroy() {
		mContext.unregisterReceiver(mLoginReceiver);
		super.onDestroy();
	}

	@Override
	protected BaseGsonRequest<FishingFriendDataTO> getRequest(Listener<FishingFriendDataTO> listener, ErrorListener errorListener) {
		String url = UriHelper.getNearFishingFriendUrl();
		UserTO user = AccountManager.getInstance(mContext).getUserTO();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_DISTANCE, String.valueOf("0"));
		params.put(UriHelper.PARAMS_PAGE_SIZE, String.valueOf(Constants.DEFAULT_PAGE_SIZE));
		params.put(UriHelper.PARAMS_PAGE_NO, String.valueOf(1));
		try {
			params.put(UriHelper.PARAMS_POINT, mLocation.getLongitude() + "," + mLocation.getLatitude());
		} catch (Exception e) {
			e.printStackTrace();
		}
		params.put(UriHelper.PARAMS_UID, user == null ? "0" : String.valueOf(user.getUid()));
		// 默认全部
		params.put(UriHelper.PARAMS_SEX, "0");
		GsonRequest<FishingFriendDataTO> request = new GsonRequest<FishingFriendDataTO>(Method.POST, url, listener, errorListener, params, FishingFriendDataTO.class);
		return request;
	}

	@Override
	protected void clearAll() {
		mAdapter.clear();
		mAdapter.notifyDataSetChanged();
	}

	@Override
	public void onResponse(FishingFriendDataTO response) {
		if (getActivity() != null) {
			super.onResponse(response);
			if (response != null) {
				List<FishingFriendTO> friends = response.getFriends();
				// 第一页
				if (response.getCurrentPage() <= 1) {
					// 保存到本地数据库缓存
					mAdapter.clear();
				}
				mAdapter.add(friends);
			} else {
				mLoadingView.setStyle(Style.EMPTY, getEmptyString());
			}
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	protected String getEmptyString() {
		return mContext.getString(R.string.no_content);
	}

	class FishingFriendAdapter extends BaseAdapter {
		private List<FishingFriendTO> mFriends = new ArrayList<FishingFriendTO>();

		@Override
		public int getCount() {
			return mFriends.size();
		}

		public void add(List<FishingFriendTO> friends) {
			if (friends != null && !friends.isEmpty()) {
				mFriends.addAll(friends);
			}
		}

		public void clear() {
			mFriends.clear();
		}

		@Override
		public Object getItem(int position) {
			return mFriends.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(mContext, R.layout.friend_item, null);
			}
			FishingFriendTO friend = mFriends.get(position);
			NetworkImageView avatarView = ViewHolder.get(convertView, R.id.avatar);
			BitmapBinder.bindCircularNetImage(mContext, avatarView, friend.getAvatar(), R.drawable.default_avatar_round_small);
			TextView sexView = ViewHolder.get(convertView, R.id.sex);
			int sex = friend.getSex();
			if (sex == Constants.SEX_FEMALE) {
				sexView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.sex_female, 0, 0, 0);
				sexView.setTextColor(mContext.getResources().getColor(R.color.sex_color_female));
			} else {
				sexView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.sex_male, 0, 0, 0);
				sexView.setTextColor(mContext.getResources().getColor(R.color.sex_color_male));
			}
			Date date = DateUtil.getDateObj(friend.getBirthday(), DateUtil.PATTERN_YMD);
			int age = (int) ((System.currentTimeMillis() - date.getTime()) / (365L * 24 * 60 * 60 * 1000));
			sexView.setText(String.valueOf(age));
			TextView nicenameView = ViewHolder.get(convertView, R.id.nickname);
			nicenameView.setText(friend.getNickname());
			TextView moodView = ViewHolder.get(convertView, R.id.mood);
			moodView.setText(friend.getMood());
			TextView distanceView = ViewHolder.get(convertView, R.id.distance);
			distanceView.setVisibility(View.VISIBLE);
			distanceView.setText(getString(R.string.distance_format, formatDistance(friend.getDistance())));

			ImageView followBtn = ViewHolder.get(convertView, R.id.follow);
			followBtn.setVisibility(View.VISIBLE);
			if (friend.isFollowed()) {
				followBtn.setImageResource(R.drawable.list_btn_followed);
			} else {
				followBtn.setImageResource(R.drawable.list_btn_add_follow);
			}
			followBtn.setTag(friend);
			followBtn.setOnClickListener(mFollowListener);
			return convertView;
		}

	}

	private OnClickListener mFollowListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Object tag = v.getTag();
			if (tag != null && tag instanceof FishingFriendTO) {
				FishingFriendTO friend = (FishingFriendTO) tag;
				onFollowClick(friend);
			}
		}
	};

	private void onFollowClick(final FishingFriendTO friend) {
		AccountManager accountManager = AccountManager.getInstance(mContext);
		if (!accountManager.isLogined()) {
			UiUtil.showNoLoginDialog(this, -1, LoginActivity.ACTION_RETURN);
			return;
		} else {
			UserTO user = accountManager.getUserTO();
			if (user.isExpired()) {
				Toast.makeText(mContext, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
				LoginActivity.start(getActivity(), -1, LoginActivity.ACTION_RETURN);
			} else {
				final boolean isFollowed = friend.isFollowed();
				String url = isFollowed ? UriHelper.getRemoveFollowUrl() : UriHelper.getAddFollowUrl();
				HashMap<String, String> params = new HashMap<String, String>();
				params.put(UriHelper.PARAMS_TOKEN, user.getToken());
				params.put(UriHelper.PARAMS_MATCH_ID, String.valueOf(friend.getUid()));
				params.put(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
				GsonRequest<BaseTO> request = new GsonRequest<BaseTO>(Method.POST, url, new Listener<BaseTO>() {

					@Override
					public void onResponse(BaseTO response) {
						if (getActivity() != null) {
							if (response != null) {
								if (response.isSuccess()) {
									mContext.sendBroadcast(new Intent(Constants.INTENT_ACITON_FRIEND_CHANGED));
									friend.setFollowed(!friend.isFollowed());
									int resId = isFollowed ? R.string.remove_follow_success : R.string.add_follow_success;
									Toast.makeText(mContext, resId, Toast.LENGTH_SHORT).show();
									mAdapter.notifyDataSetChanged();
								} else {
									if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
										Toast.makeText(mContext, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
										LoginActivity.start(getActivity(), -1, LoginActivity.ACTION_RETURN);
									} else {
										String msg = response.getMsg();
										String str = isFollowed ? mContext.getString(R.string.remove_follow_failed) : mContext.getString(R.string.add_follow_failed);
										msg = TextUtils.isEmpty(msg) ? str : msg;
										Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
									}
								}
							} else {
								int resId = isFollowed ? R.string.remove_follow_failed : R.string.add_follow_failed;
								Toast.makeText(mContext, resId, Toast.LENGTH_SHORT).show();
							}
						}
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						if (getActivity() != null) {
							Toast.makeText(mContext, R.string.request_error, Toast.LENGTH_SHORT).show();
						}
					}
				}, params, BaseTO.class);
				RequestManager.startRequest(mContext, request);
			}
		}

	}

}
